var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/web/index');
//导入account接口路由文件
const accounterRouter = require('./routes/api/account')
//导入路由文件
const authRouter = require('./routes/web/auth')
const authApiRouter = require('./routes/api/auth')
//导入session依赖包
const session = require("express-session");
const MongoStore = require("connect-mongo");
//导入配置项
const {DBHOST,DBPORT,DBNAME} = require('./config/config');
var app = express();
//设置session的中间件
app.use(session({
    name:'sid',//设置响应cookie的名字
    secret: 'your-secret-key', // 用于加密 session ID 的密钥
    saveUninitialized: true, // 设置是否为每一次请求都自动创建一个session对象
    resave: true, // 重新保存，只要往服务端发送请求，就重新村一次，延迟销毁时间
    store:MongoStore.create({//设置mongodb的连接，到时候会把session数据保存到数据库bilibili
        mongoUrl:`mongodb://${DBHOST}:${DBPORT}/${DBNAME}`
    }),
    cookie: {
        httpOnly:true,//前端不能操作cookie,cookie只用于传输
        maxAge:1000*60*60*24*7//生命周期
    }
}));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/', authRouter);
app.use('/api', accounterRouter);
app.use('/api', authApiRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
